package whu.cn.whushare.ui.main.known;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.User;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.common.ImageWorkerManager;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.main.known.bean.Answer;
import whu.cn.whushare.ui.main.known.bean.AnswerWrapBean;
import whu.cn.whushare.ui.main.known.bean.FavorBean;
import whu.cn.whushare.ui.main.known.bean.VoteBean;
import whu.cn.whushare.ui.main.my.bean.MyAnswer;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.dd.processbutton.iml.ActionProcessButton;

import java.io.InputStream;
import java.net.URL;

@ViewMapping(id = R.layout.activity_known_answer_detail)    //获取activity_known_answer_detail布局文件
public class AnswerDetailActivity extends BaseActivity {
	@ViewMapping(id = R.id.question)                        //获取问题标题
	private TextView mTitleTxt;
	@ViewMapping(id = R.id.answer_person)                   //获取回答者头像
	private ImageView mAvatar;
	@ViewMapping(id = R.id.answer_person_name)              //获取回答用户姓名
	private TextView mUserNameTxt;
	@ViewMapping(id = R.id.agree_num)                       //获取投票框
	private TextView mAgreeNumTxt;
	@ViewMapping(id = R.id.answer_content)                  //获取回答内容
	private TextView mAnswerContent;
	@ViewMapping(id = R.id.first_btn)                       //获取“分享”按钮
	private Button mShareBtn;
	@ViewMapping(id = R.id.second_btn)                      //获取“收藏”按钮
	private ActionProcessButton mFavorBtn;
	@ViewMapping(id = R.id.third_btn)                       //获取“评论”按钮
	private Button mCommentBtn;

	private boolean mIsFavored;
	private String mQuestionId;
	private User mAnswerUser;
	private Answer mAnswer;
	private String mTitle;
	private AlertDialog dialog;
    private String html2="<p>";

	public static Intent getStartIntent(Context context, String questionId, String title, AnswerWrapBean answerWrapBean) {
		Intent i = new Intent(context, AnswerDetailActivity.class);
		i.putExtra(Constants.INTENT_EXTRA_ANSWER_WRAP, answerWrapBean);
		i.putExtra(Constants.INTENT_EXTRA_QUESTION_ID, questionId);
		i.putExtra(Constants.INTENT_EXTRA_QUESTION, title);
		return i;
	}


	@Override
    //activity启动时调用该方法，主要完成一些初始化操作
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getIntentData();
		initView();
	}

    //获取intent中的数据
	private void getIntentData() {
		if (getIntent() != null) {
			mQuestionId = getIntent().getStringExtra(Constants.INTENT_EXTRA_QUESTION_ID);
			AnswerWrapBean mAnswerWrap = getIntent().getParcelableExtra(Constants.INTENT_EXTRA_ANSWER_WRAP);
			mAnswerUser = mAnswerWrap.user;
			mAnswer = mAnswerWrap.answer;
			mTitle = getIntent().getStringExtra(Constants.INTENT_EXTRA_QUESTION);
		}
	}

    //初始化views
	private void initView() {
		View root = ViewMappingUtil.mapView(this, this);
		SetOnClickUtil.registerOnClick(this);
		getTopBar(root);
		mTopBar.searchLayout.setVisibility(View.VISIBLE);
		mFavorBtn.setMode(ActionProcessButton.Mode.ENDLESS);
        //加载回答用户头像
		ImageWorkerManager.getInstance(this).loadCommonImage(Utils.getPhotoUrl(mAnswerUser.getAvatar()), mAvatar,
				R.drawable.avatar, R.drawable.avatar);
		mTitleTxt.setText(TextUtils.isEmpty(mTitle) ? mAnswer.getQuestion() : mTitle);
		mUserNameTxt.setText(mAnswerUser.getNickName());
        //设置点赞数
		mAgreeNumTxt.setText(mAnswer.getVoteCount() + "");
        final String html= mAnswer.answerContext+"";
        if(html!=""&&html.length()>3) {
            if (html.substring(0, 3).equals("<p>"))
            {
                String[] html1 = html.split(">");
                for (int i = 1; i < html1.length; i++) {
                    html2 = html2 + html1[i] + ">" + "<br>";
                }
            }
            else
                html2=html;
        }
        else
        {

            html2 = html;

        }

        final String html3=html2;
        //新建一个异步任务，用于加载回答内容
        new AsyncTask<String,String,Spanned>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Spanned s) {
                super.onPostExecute(s);
                mAnswerContent.setText(s);
            }

            @Override
            protected Spanned doInBackground(String... params) {
                Spanned sp = Html.fromHtml(html3,
                        new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                source = "http://www.027team.com" + source;
                                InputStream is = null;
                                try {
                                    is = new URL(source).openStream();
                                    Drawable d = Drawable.createFromStream(is, "src");
                                    d.setBounds(0, 0, d.getIntrinsicWidth()*3, d.getIntrinsicHeight()*3);
                                    is.close();
                                    return d;
                                } catch (Exception e) {
                                    return null;
                                }
                            }
                        }, null);
                return sp;
            }
        }.execute();

		mCommentBtn.setText(mAnswer.getCommentNum() + "");
	}

	@Override
    /**
     * 网络请求成功时调用该函数，
     * 当网络请求类型为“收藏”时，进行“收藏”或“取消收藏”成功操作
     * 当网络请求类型为“投票”时，进行“投票”成功后的操作
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
		switch (type) {
		case FAVOR:
			FavorBean favorBean = (FavorBean) response;
			mIsFavored = favorBean.type.equals("add");
			processBtnEnd();
			break;
		case VOTE:
			VoteBean voteBean = (VoteBean) response;
			if ("voted".equals(voteBean.status)) {
				toast("您已经投过票");
			} else {
				toast("投票成功");
				mAgreeNumTxt.setText((mAnswer.getVoteCount() + 1) + "");
			}
			break;
		default:
			break;
		}
	}

	@Override
    /**
     * 网络请求失败时调用该函数，
     * 当网络请求类型为“收藏”时，进行“收藏”或“取消收藏”失败操作
     * 当网络请求类型为“投票”时，进行“投票”失败后的操作
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		switch (type) {
		case FAVOR:
			if (TextUtils.isEmpty(msg)) {
				toast(mIsFavored ? R.string.cancel_favor_fail : R.string.favor_fail);
			} else {
				toast(msg);
			}
			processBtnEnd();
			break;
		case VOTE:
			if (TextUtils.isEmpty(msg)) {
				toast("投票失败");
			} else {
				toast(msg);
			}
			break;
		default:
			break;
		}
	}

	private void processBtnEnd() {
		mFavorBtn.setProgress(100);
		mFavorBtn.setText(mIsFavored ? R.string.favor : R.string.cancel_favor);
		mFavorBtn.setEnabled(true);
	}

	@Override
    /**
     * 方法名：onClick(View v)
     * 功 能：根据发生点击事件的控件不同处理不同的点击事件
     *        控件为“分享”按钮时，弹出提示信息
     *        控件为“收藏”按钮时，进行问题收藏操作
     *        控件为“评论”按钮时，跳转到CommentListActivity
     *        控件为“点赞”按钮时，显示点赞数弹框
     * 参 数：@param v - 发生点击事件的控件
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.first_btn:
			toast(R.string.no_support);
			break;
		case R.id.second_btn:
			mFavorBtn.setEnabled(false);
			requestFavorQuestion();
			break;
		case R.id.third_btn:
			startActivity(CommentListActivity.getStartIntent(this, mQuestionId, mAnswer.id));
			break;
		case R.id.agree_num:
			showVoteDialog();
			break;
		default:
			break;
		}
	}

    /**
     * 显示投票弹框
     * 当点击“赞成”按钮时，投票数加1
     * 当点击“反对”按钮时，投票数减1
     */
	private void showVoteDialog() {
		if (dialog == null) {
			dialog = new AlertDialog.Builder(this).setPositiveButton("赞成", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();   //取消对话框
					getVote(1);
				}
			}).setNegativeButton("反对", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getVote(-1);
					dialog.dismiss();
				}
			}).create();
		}
		if (!isFinishing()) {
			dialog.show();
		}
	}

    /**
     * 请求投票
     * @param value - 投票数
     */
	private void getVote(int value) {
		Downloader.getInstance(this).requestVote(mAnswer.getId(), value, this);
	}

    //创建收藏问题的请求
	private void requestFavorQuestion() {
		Downloader.getInstance(this).requestFavor(mQuestionId, this);
		mFavorBtn.setProgress(50);
	}
}
